public class LongestPalindromeByDP {
    public String longestPalindrome(String s) {
        if(s.isEmpty()||s.length()<2)return s;
        int len = s.length();
        int maxLen=1;
        int begin=0;
        boolean dp[][]=new boolean[len][len];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                dp[i][j]=true;
            }
        }
        char[] charArray = s.toCharArray();
        for (int curLen = 2; curLen <=len; curLen++) {
            for (int i = 0; i < len; i++) {
                int j=i+curLen-1;
                if(j>=len)break;
                if(charArray[i]!=charArray[j])
                {
                    dp[i][j]=false;
                }else{
                    if(j-i<3){
                        dp[i][j]=true;
                    }else{
                        dp[i][j]=dp[i+1][j-1];
                    }
                }
                if(dp[i][j]&&j-i+1>maxLen){
                    maxLen=j-i+1;
                    begin=i;
                }
            }

        }
        return s.substring(begin,begin+maxLen);
    }
}
